package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import pojo.Book;
import pojo.Order;
import utils.DBUtil;

public class ShopDaoImpl implements ShopDao {
	

	@Override
	public List<Book> loadAllBooks() {
		List<Book> list=new ArrayList<Book>();
		String sql = "select * from s_book";
		Connection con=null;
		PreparedStatement pst = null;
		ResultSet rs =null;
		try {
			con=DBUtil.getConnection();
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			while(rs.next()) {
				Book b=new Book();
				String bid = rs.getString("bid");
				String bname = rs.getString("bname");
				double price = rs.getDouble("price");
				String image = rs.getString("image");
				b.setBid(bid);
				b.setBname(bname);
				b.setPrice(price);
				b.setImage(image);
				list.add(b);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, rs);
		}
		return list;
	}

	@Override
	public List<Book> loadAllOrders() {
		return null;
	}

	@Override
	public int findUser(String name) {
		return 0;
	}

	@Override
	public Book loadBook(String bid) {
		Book b=null;
		
		String sql = "select * from s_book where bid=?";
		Connection con=null;
		PreparedStatement pst = null;
		ResultSet rs =null;
		try {
			con=DBUtil.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, bid);;
			rs = pst.executeQuery();
			if (rs.next()) {
				b = new Book();
				String bname = rs.getString("bname");
				double price = rs.getDouble("price");
				String image = rs.getString("image");
				b.setBid(bid);
				b.setBname(bname);
				b.setPrice(price);
				b.setImage(image);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(null, pst, rs);
		}
		return b;
	}

	@Override
	public int addOrder(Order o) {
		String sql = "insert into s_order(oid,bid,count,o_date) values(?,?,?,?)";
		Connection con=null;
		PreparedStatement pst = null;
		int m = 0;
		try {
			con=DBUtil.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, o.getOid());
			pst.setString(2, o.getBid());
			pst.setInt(3, o.getCount());
			pst.setDate(4, new java.sql.Date(o.getoDate().getTime()));
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, null);
		}
		return m;
	}


	

}
